<template>
    <el-dialog :title="editOrAdd=='edit' ? '编辑员工' : '新增员工'" :visible="dialogEdit" @close="close">
        <el-form ref="form" label-width="100px" :rules="rules" :model="form">
            <el-form-item label="员工姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入员工姓名"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-select clearable class="filter-item" placeholder="请选择性别" v-model="form.gender" style="width: 100%;">
                    <el-option v-for="(item, index) in genderOptions" :key="item.name" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属岗位" prop="role">
                <el-select clearable class="filter-item" placeholder="请选择所属岗位" v-model="form.role" style="width: 100%;">
                    <el-option v-for="(item, index) in roleOptions" :key="item.name" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="phone" v-if="editOrAdd=='add'">
                <el-input v-model="form.phone" placeholder="请输入手机号" :maxlength="phoneMaxLength"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pwd" v-if="editOrAdd=='add'">
                <el-input v-model="form.pwd" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="所属医院" prop="hid" v-if="form.role == 1 || form.role == 2">
                <el-select clearable class="filter-item" placeholder="请选择所属医院" v-model="form.hid" style="width: 100%;">
                    <el-option v-for="(item, index) in hospitalOptions" :key="item.name" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属分组" prop="gid">
                <el-select clearable class="filter-item" placeholder="请选择所属分组" v-model="form.gid" style="width: 100%;">
                    <el-option v-for="(item, index) in groupOptions" :key="item.name" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="onSubmit('form')">保存</el-button>
            <el-button plain @click="close">取消</el-button>
        </span>
    </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { roles } from '@/utils/role'
  import { fetchHospitalList } from '@/api/hospital'
  import { userGet, userUpdate, userAdd } from '@/api/user'
  import { factoryGroupGetList } from '@/api/factory'

  // name 用户名 必填
  // gender 性别 选填 1男 0 女
  // role 角色 必填
  // phone 手机号 必填
  // pwd 密码 必填
  // hid 所属医院 选填 角色是驻场负责人和驻场员工时必填
  // gid 分组id 选填 角色是工厂组长 和 工厂员工时必填
  export default {
    name: 'EmployeeManage',
    props: ['employeeId', 'editOrAdd', 'dialogEdit'],
    data() {
      return {
        defaultForm: {
          name: '',
          gender: '',
          role: '',
          phone: '',
          pwd: '',
          hid: '',
          gid: ''
        },
        form: {
          name: '',
          gender: '',
          role: '',
          phone: '',
          pwd: '',
          hid: '',
          gid: ''
        },
        isEdit: false,
        phoneMaxLength: 11,
        hospitalOptions: [],
        roleOptions: roles,
        groupOptions: [],
        genderOptions: [{ name: '男', id: '1' }, { name: '女', id: '0' }],
        rules: {
          name: [
            { required: true, message: '请输入员工姓名', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ],
          gender: [
            { required: true, message: '请选择性别', trigger: 'blur' }
          ],
          role: [
            { required: true, message: '请选择岗位', trigger: 'blur' }
          ]
        }
      }
    },
    created: function() {
      this.form = this.defaultForm
      this.getHospital()
      this.getGroup()
    },
    watch: {
      dialogEdit(val) {
        if (val) {
          this.initForm()
        }
      }
    },
    computed: {
      ...mapGetters([
        'fid'
      ])
    },
    methods: {
      getHospital() {
        fetchHospitalList({ page: 1, size: 500 }).then(response => {
          this.hospitalOptions = response.data && response.data.list || []
        })
      },
      getGroup() {
        factoryGroupGetList({ page: 1, size: 500 }).then(response => {
          this.groupOptions = response.data && response.data.list || []
        })
      },
      initForm() {
        if (this.editOrAdd === 'add') {
          this.isEdit = false
          this.form = this.defaultForm
          this.$nextTick(() => {
            this.$refs['form'] && this.$refs['form'].resetFields()
          })
        } else {
          this.isEdit = true
          this.getInfo()
          this.$nextTick(() => {
            this.$refs['form'] && this.$refs['form'].clearValidate()
          })
        }
      },
      getInfo() {
        userGet({ id: this.employeeId }).then(response => {
          if (response) {
            this.form = response.data
            this.form.gid = '' + this.form.gid === '0' ? '' : this.form.gid
            this.form.hid = '' + this.form.hid === '0' ? '' : this.form.hid
          }
        })
      },
      close() {
        this.$emit('update:dialogEdit', false)
      },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.isEdit) {
              var param = { name: this.form.name, gender: this.form.gender, role: this.form.role, id: this.form.id }
              if ([1, 2, '1', '2'].indexOf(this.form.role) > -1) {
                if (!this.form.hid) {
                  this.$message({ message: '请选择所属医院', type: 'error', showClose: true })
                  return
                }
                param.hid = this.form.hid
              }
              param.gid = this.form.gid
              userUpdate(param).then(response => {
                if (response) {
                  this.$message({ message: '修改员工成功', type: 'success', showClose: true })
                  this.$emit('update:dialogEdit', false)
                  this.$emit('refreshList')
                }
              })
            } else {
              this.form.region = this.region
              var params = { fid: this.fid, name: this.form.name, gender: this.form.gender, role: this.form.role, phone: this.form.phone, pwd: this.form.pwd }
              if (!this.form.phone || !/^1\d{10}$/.test(this.form.phone)) {
                this.$message({ message: '请输入正确的手机号', type: 'error', showClose: true })
                return
              }
              if (!this.form.pwd) {
                this.$message({ message: '请输入密码', type: 'error', showClose: true })
                return
              }
              if ([1, 2, '1', '2'].indexOf(this.form.role) > -1) {
                if (!this.form.hid) {
                  this.$message({ message: '请选择所属医院', type: 'error', showClose: true })
                  return
                }
                params.hid = this.form.hid
              }
              params.gid = this.form.gid
              userAdd(params).then(response => {
                if (response) {
                  this.$message({ message: '添加员工成功', type: 'success', showClose: true })
                  this.$emit('update:dialogEdit', false)
                  this.$emit('refreshList')
                }
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
  }
</script>
